import datetime
import json
import uuid

from django.shortcuts import HttpResponse
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView

from resourcesShare.models import *
from movie.models import *
from rest_framework.pagination import PageNumberPagination


# Create your views here.

class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class ApiMiddlewareMixin(MiddlewareMixin):
    def process_response(self, request, response):
        # 添加响应头
        # response["xxx"]=9999
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "Content-type"
        response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS,DELETE,PUT"

        return response


class ResourceSerializers(serializers.ModelSerializer):
    tag = serializers.CharField(source='get_tag_display')
    # user = serializers.CharField(source="user.user")
    user = serializers.SerializerMethodField()

    class Meta:
        model = Resource
        # fields="__all__"
        fields = "__all__"

    def get_user(self, obj):
        tmp = {}
        tmp["id"] = obj.user.id
        tmp["nickname"] = obj.user.nickname
        tmp["user"] = obj.user.user

        return tmp


class ResourcePostSerializers(serializers.ModelSerializer):
    # tag = serializers.CharField(source='get_tag_display')
    # user=serializers.CharField(source="user.user")
    class Meta:
        model = Resource
        fields = "__all__"



class ResourceDteailViewSet(APIView):
    def get(self, requset, id):

        resource_obj = Resource.objects.filter(pk=id).first()
        resource_obj = ResourceSerializers(resource_obj)
        return Response(resource_obj.data)

    def delete(self, requset, id):
        token=requset.query_params.get("token")
        token_obj=UserToken.objects.get(token=token)
        if not token_obj:
            return Response("没有权限")
        Resource.objects.filter(pk=id).delete()
        # print(id)
        return Response("")

    def put(self, requset, id):
        ret = {"code": 1000}
        token = requset.query_params.get("token")
        token_obj = UserToken.objects.get(token=token)
        if not token_obj:
            return Response("没有权限")
        resource_obj = Resource.objects.get(pk=id)
        resource_obj_json = ResourcePostSerializers(resource_obj, data=requset.data)


        if resource_obj_json.is_valid():
            resource_obj_json.save()
            ret["resource"] = resource_obj_json.data
            return Response(ret)
        else:
            return Response(resource_obj_json.errors)


class ResourceViewSet(APIView):
    def get(self, requset):
        resource_list = Resource.objects.all().order_by('-id', )
        tmp = ResourceSerializers(resource_list, many=True)
        return Response(tmp.data)

    def post(self, requset):
        token = requset.query_params.get("token")
        token_obj = UserToken.objects.get(token=token)
        if not token_obj:
            return Response("没有权限")
        ret = {"code": 1000}
        tmp = requset.data
        date = str(datetime.datetime.now().date())
        tmp["date"] = date

        resource_serializers = ResourcePostSerializers(data=tmp)

        if resource_serializers.is_valid():
            # print(resource_serializers)
            resource_obj=resource_serializers.save()
            resource_RS=ResourceSerializers(resource_obj)

            ret["msg"] = "添加成功"

            ret['resource'] = resource_RS.data
            # print(ret['resource'])
            return Response(ret)
        else:
            # print(resource_serializers.errors)
            return Response(resource_serializers.errors)


class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["user", "password"]


class UserViewSet(APIView):
    def post(self, requset):
        ret = {"code": 1000}
        # print(requset.data)
        user = requset.data.get("user")
        password = requset.data.get("password")
        user = User.objects.filter(password=password, user=user).first()

        if not user:

            ret["code"] = 2000
            ret["error"] = "账户或密码错误"
        else:
            uid = str(uuid.uuid4())
            UserToken.objects.update_or_create(user=user, defaults={"token": uid})
            ret["token"] = uid
            ret["nickname"] = user.nickname
            ret["user_id"] = user.pk
        return Response(ret)

    def get(self, requset):
        user = User.objects.all()
        tmp = ResourceSerializers(user, many=True)
        return Response(tmp.data)
        # return HttpResponse("...")


# 注册账户

# class UserForm(forms.Form):
#     user = models.CharField(unique=True, max_length=32)
#     password = models.CharField(max_length=4)
#     nickname = models.CharField(max_length=32)
#     email = models.EmailField()


class UserSerializers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"


class RegisteredViewSet(APIView):

    def post(self, requset):
        ret = {"code": 1000}
        # print(request.data)
        serializers = UserSerializers(data=requset.data)
        # print(serializers)
        if serializers.is_valid():
            serializers.save()
            ret["msg"] = "注册成功"
            return Response(ret)
            # print("ok")
        else:
            # print("no")
            # print(serializers.errors)
            return Response(serializers.errors)
        # return  Response


def tag(requset):
    tag_list = Resource.tag_choices
    tag_dic = []
    for i in tag_list:
        tag_dic.append({"id": i[0], "tag": i[1]})
        # tag_dic["tag"]=i[1]
    # print(tag_dic)
    tag_dic = json.dumps(tag_dic)
    return HttpResponse(tag_dic)




class MovieinfoPagination(PageNumberPagination):
    page_size = 15
    page_query_param = "page"
    page_size_query_param = "size"

class MovieinfoSerializers(serializers.ModelSerializer):
    class Meta:
        model = Movieinfo
        fields = "__all__"


class MovieinfoViewSet(APIView):
    def get(self,requset):
        ret={"code":1000}
        movie_obj_list=Movieinfo.objects.all().order_by("-id")
        page_handler=MovieinfoPagination()
        page_page_movie_obj_list=page_handler.paginate_queryset(movie_obj_list,requset,self)

        tmp=MovieinfoSerializers(page_page_movie_obj_list, many=True)
        ret["pageSize"]=len(page_page_movie_obj_list)
        ret["total"]=len(movie_obj_list)
        ret["moveinfo"]=tmp.data
        # print(movieinfo_serializers)
        return Response(ret)


def test(requset):
    obj = Resource.objects.get(id=1)
    # print(obj.title)
    # print(obj.tag)
    # print("get_tag_display",obj.get_tag_display())
    return HttpResponse("...")


